package cmq.socket;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;

/**
 * @ProjectName: interview
 * @Package: cmq.socket
 * @ClassName: NIOServer
 * @Author: chenmengqi
 * @Description:
 * @Date: 2020/2/18 11:11 下午
 * @Version: 1.0
 */
public class NIOServer {
    public static void main(String[] args) {
        HashSet<SocketChannel> socketChannels = new HashSet<>();
        try {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.bind(new InetSocketAddress(3000));

            serverSocketChannel.configureBlocking(false);

            while (true) {

                // 阻塞，并获取连接
                SocketChannel accept = serverSocketChannel.accept();

                if (accept == null) {
                    Thread.sleep(1000);
                    System.out.println("no new connect");

                    System.out.println("连接数量：" + socketChannels.size());

                    for (SocketChannel channel : socketChannels) {

                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

                        channel.read(byteBuffer);
                        byteBuffer.flip();

                        System.out.println(StandardCharsets.UTF_8.decode(byteBuffer));

                        channel.close();

                        socketChannels.remove(channel);
                    }
                } else {
                    accept.configureBlocking(false);
                    socketChannels.add(accept);
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
